package com.ruoyi.heytalk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.constant.heytalk.CommonConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.heytalk.*;
import com.ruoyi.common.core.domain.heytalk.dto.SearchUserDTO;
import com.ruoyi.common.core.domain.heytalk.vo.LoginImUser;
import com.ruoyi.common.core.domain.heytalk.vo.SearchUserVO;
import com.ruoyi.common.core.domain.heytalk.vo.UserDetailVO;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.service.HeyTalkTokenService;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.heytalk.mapper.ImUserMapper;
import com.ruoyi.heytalk.service.*;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息Service业务层处理
 * 
 * @author zhusy
 * @since 2021-10-17
 */
@Service
@DataSource(DataSourceType.SLAVE)
public class ImUserServiceImpl extends ServicePlusImpl<ImUserMapper, ImUser, ImUser> implements IImUserService {

    @Resource
    private IImMomentService momentService;

    @Resource
    private IImFriendService friendService;

    @Resource
    private HeyTalkTokenService tokenService;

    @Resource
    private IImFriendTagService friendTagService;

    @Resource
    private IImTagService tagService;

    /**
     * 校验微信号是否重复
     * @param id 用户唯一ID
     * @param userName 微信号
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String id, String userName){
        String idValue = StringUtils.isIdNull(id);
        ImUser info = this.getOne(new LambdaQueryWrapper<ImUser>().eq(StrUtil.isNotBlank(userName), ImUser::getUserName, userName));
        if (!Objects.isNull(info) && !idValue.equals(info.getId())) {
            return CommonConstants.NOT_UNIQUE;
        }
        return CommonConstants.UNIQUE;
    }

    @Override
    public AjaxResult<SearchUserVO> searchUser(SearchUserDTO searchUserDTO) {
        ImUser info = this.getOne(new LambdaQueryWrapper<ImUser>().eq(ImUser::getUserName, searchUserDTO.getKeyword()));
        SearchUserVO searchUserVO = new SearchUserVO();
        BeanUtil.copyProperties(info, searchUserVO);
        searchUserVO.setUserId(info.getId());
        return AjaxResult.success(searchUserVO);
    }

    @Override
    public AjaxResult<UserDetailVO> getUserInfo(String userId) {
        ImUser imUser = this.getById(userId);
        if (Objects.isNull(imUser) || Objects.equals(CommonConstants.UserStatusEnum.NORMAL.getCode(), imUser.getStatus())) {
            return AjaxResult.error(MessageUtils.message("heyTalk.user.not.or.disable"), null);
        }
        LoginImUser loginImUser = tokenService.getLoginImUser(ServletUtils.getRequest());
        ImFriend imFriend = friendService.getOne(new LambdaQueryWrapper<ImFriend>()
                .eq(ImFriend::getFriendId, userId)
                .eq(ImFriend::getUserId, loginImUser.getUserId()));
        UserDetailVO userDetailVO = UserDetailVO.builder()
                .userId(userId)
                .userName(imUser.getUserName())
                .nickName(imUser.getNickName())
                .avatar(imUser.getAvatar())
                .sex(imUser.getSex())
                .sign(imUser.getSign())
                .area(imUser.getArea()).build();
        if (!Objects.isNull(imFriend)) {
            //查找前三条朋友圈数据
            List<ImMoment> momentList = momentService.list(new LambdaQueryWrapper<ImMoment>()
                    .eq(ImMoment::getUserId, userId)
                    .orderByDesc(ImMoment::getCreateTime)
                    .last("limit 3"));
            //取出朋友的tag标签
            List<String> friendTagIds = friendTagService.list(new LambdaQueryWrapper<ImFriendTag>().eq(ImFriendTag::getFriendId, imFriend.getId()))
                    .stream().map(ImFriendTag::getTagId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(friendTagIds)) {
                userDetailVO.setTags(tagService.list(new LambdaQueryWrapper<ImTag>().in(ImTag::getId, friendTagIds)));
            }
            userDetailVO.setFriend(true);
            userDetailVO.setLookMe(imFriend.getLookMe());
            userDetailVO.setLookHim(imFriend.getLookHim());
            userDetailVO.setStar(imFriend.getStar());
            userDetailVO.setIsBlack(imFriend.getIsBlack());
            userDetailVO.setMoments(momentList);
        }
        return AjaxResult.success(userDetailVO);
    }

}
